package com.zjl.service.impl;

import com.zjl.domain.WalletRecord;
import com.zjl.mapper.WalletMapper;
import com.zjl.mapper.WalletRecordMapper;
import com.zjl.service.WalletRecordService;
import com.zjl.service.WalletService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Author EternalPain
 * @Date 2023/1/31 18:17
 * @Version 1.0
 */
@Service
public class WalletServiceImpl implements WalletService {

    @Resource
    public WalletMapper walletMapper;
    @Resource
    public WalletRecordService recordService;
    @Resource
    public WalletRecordMapper recordMapper;

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public boolean consumeMoney(int userId, BigDecimal money) {
        if (!walletMapper.consumeMoney(userId, money)) {
            return false;
        }

        // 添加消费记录
        WalletRecord record = new WalletRecord(userId, true, money);
        recordService.addRecord(record);

        return true;
    }

    /**
     * 按正常逻辑退款应该是对消费记录进行退款
     * 因为没有商品部分的代码，所有我这先添加一条消费20元记录，然后退款
     **/
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public boolean refund(int userId, BigDecimal money) {
        // 消费20元
        WalletRecord record = new WalletRecord(userId, true, money);
        recordService.addRecord(record);

        // 退款
        return recordMapper.refund(record.getWalletRecordId());
    }
}
